<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BScreenMakeQueue
 *
 * @author I062261
 */
class BScreenMakeQueue extends BUIScreen {

    public $makeQueueFormModel = null;

    public function render($data = null) {

        $this->makeQueueFormModel = new MakeQueueFormModel('makeQueue');

        //parent::render($data);
        $this->addRenderView('makeQueue', 'makeQueueView', array('screen' => $this));
        //$this->startRender();
    }

    public function populateQueueLineLinks($ajaxPlace = null) {
        $qlineLinks = array();
        $qLines = Blyn::app()->getActiveServiceApp()->getQueueLines();
        if ($qLines == NULL)
            return array();

        //      $isLinkClicked = FALSE;
        $activeId = $this->getTransitVariable('activeQueueLineId');
        $activeId = isset($_REQUEST['queueLineId']) ? $_REQUEST['queueLineId'] : $activeId;
        if ($activeId == NULL) {
            reset($qLines);
            foreach ($qLines as $qLine) {
                $transactions = $qLine->getTransactions(array('makeQueueTime' => time()));
                if (count($transactions) > 0) {
                    $activeId = $qLine->id;
                    break;
                }
            }
        }
        $this->addTransitVariable('activeQueueLineId', $activeId);

        foreach ($qLines as $qLine) {
            $qLineLink = array();
            $qLineLink['id'] = $qLine->id;
            $qLineLink['active'] = FALSE;
            //first set active link
            if ($activeId == $qLine->id)
                $qLineLink['active'] = TRUE;
            $link = $this->buildLink('queueLine' . $qLine->id, $qLine->name, BUIScreen::LinkType_AjaxLink, NULL, array('queueLineId' => $qLine->id));
            $qLineLink['ajaxLink'] = $link;
            $qlineLinks[$qLine->id] = $qLineLink;
        }

        return $qlineLinks;
    }

    public function populateMakeQueueLink($makeQueueStatus) {

        $link = $this->buildLink('makeQueueLink', "Make A Queue", BUIScreen::LinkType_AjaxButton);

        //means make queue already
        if (isset($makeQueueStatus['queueNumber'])) {
            if ($makeQueueStatus['processQueueStatus'] == BAQQueueLine::processQueueStatus_Pending)
                $link = $this->buildLink('cancelQueueLink', "Cancel Your Queue", BUIScreen::LinkType_AjaxButton);

            if ($makeQueueStatus['processQueueStatus'] == BAQQueueLine::processQueueStatus_Processed)
                $link = $this->buildLink('makeQueueLink', "Make A Queue", BUIScreen::LinkType_AjaxButton);

            if ($makeQueueStatus['processQueueStatus'] == BAQQueueLine::processQueueStatus_Processing)
                $link = $this->buildLink('cancelQueueLink', "Processing Your Queue", BUIScreen::LinkType_AjaxButton, NULL, NULL, array('class' => 'disabled'));
        }

        return $link;
    }

    public function populateMakeQueueMessage($makeQueueStatus) {

        $message = NULL;

        //means make queue already
        if (isset($makeQueueStatus['queueNumber'])) {
            if ($makeQueueStatus['processQueueStatus'] == BAQQueueLine::processQueueStatus_Pending)
                $message = $makeQueueStatus['message'];

            if ($makeQueueStatus['processQueueStatus'] == BAQQueueLine::processQueueStatus_Processed)
                $link = $this->buildLink('makeQueueLink', "Make A Queue", BUIScreen::LinkType_AjaxButton);

            if ($makeQueueStatus['processQueueStatus'] == BAQQueueLine::processQueueStatus_Processing)
                $link = $this->buildLink('cancelQueueLink', "Processing Your Queue", BUIScreen::LinkType_AjaxButton, NULL, NULL, array('class' => 'disabled'));
        }

        return $message;
    }

    protected function makeQueue($data = array()) {
        $count = BMServiceQueueLineTransactionQueue::model()->countByAttributes(array('transaction_id' => $data['transactionId']));
        $mTransQueue = new BMServiceQueueLineTransactionQueue();
        $mTransQueue->transaction_id = $data['transactionId'];
        $mTransQueue->queue_number = $count + 1;
        $mTransQueue->queue_member_id = Blyn::app()->getCurrentUser()->getId();
        $mTransQueue->makequeue_status = BAQQueueLine::makeQueueStatus_MakeQueue;
        $mTransQueue->processqueue_status = BAQQueueLine::processQueueStatus_Pending;
        $mTransQueue->data = serialize(array(BAQQueueLine::makeQueueStatus_MakeQueueTime => time()));
        $mTransQueue->save();

        if (isset($data['queueMessage'])) {
            $mQueueMessage = new BMAOnlineQueueMessage();
            $mQueueMessage->queue_transaction_id = $data['transactionId'];
            $mQueueMessage->queue_number = $count + 1;
            $mQueueMessage->sender_id = Blyn::app()->getCurrentUser()->getId();
            $mQueueMessage->send_time = time();
            $mQueueMessage->data = $data['queueMessage'];
            $mQueueMessage->save();
        }
    }

    protected function cancelQueue($transactionId, $userId = NULL) {

        if ($userId == NULL)
            $userId = Blyn::app()->getCurrentUser()->getId();

        $mTranQueues = BMServiceQueueLineTransactionQueue::model()->findAllByAttributes(
                array('transaction_id' => $transactionId, 'queue_member_id' => $userId, 'makequeue_status' => BAQQueueLine::makeQueueStatus_MakeQueue));

        //return last item for queue
        $mTranQueue = end($mTranQueues);

        if ($mTranQueue != NULL) {
            $mTranQueue->makequeue_status = BAQQueueLine::makeQueueStatus_Canceled;
            $mTranQueue->processqueue_status = BAQQueueLine::makeQueueStatus_Canceled;
            $mTranQueue->data = serialize(array(BAQQueueLine::makeQueueStatus_cancelQueueTime => time()));
            $mTranQueue->save();
        }
    }

    public function checkMakeQueueStatus($transactionId, $userId = NULL, $data = array()) {

        $makeQueueStatus = array();
        $averageProcessTime = -1;
        $totalProcessTime = 0;
        $count = 0;

        if ($this->isAjaxLinkClicked('makeQueueLink')) {
            if ($this->makeQueueFormModel->makeQueueMessage != NULL)
                $this->makeQueue(array('transactionId' => $transactionId, 'queueMessage' => $this->makeQueueFormModel->makeQueueMessage));
            else {
                $this->makeQueue(array('transactionId' => $transactionId));
            }
        }

        if ($this->isAjaxLinkClicked('cancelQueueLink')) {
            $this->cancelQueue($transactionId);
        }

        $allProcessedQueues = BMServiceQueueLineTransactionQueue::model()->findAllByAttributes(
                array('transaction_id' => $transactionId, 'processqueue_status' => BAQQueueLine::processQueueStatus_Processed));

        $makeQueueStatus['processedQueue'] = count($allProcessedQueues);

        foreach ($allProcessedQueues as $processedQueue) {
            $data = unserialize($processedQueue->data);
            $startTime = $data[BAQQueueLine::processQueueStatus_StartProcessTime];
            $endTime = $data[BAQQueueLine::processQueueStatus_EndProcessTime];
            $totalProcessTime += $endTime - $startTime;
            $count++;
        }

        if ($count != 0) {
            $averageProcessTime = $totalProcessTime / $count;
            $makeQueueStatus['averageProcessTime'] = $averageProcessTime;
        }

        if ($userId == NULL)
            $userId = Blyn::app()->getCurrentUser()->getId();

        $mTranQueues = BMServiceQueueLineTransactionQueue::model()->findAllByAttributes(
                array('transaction_id' => $transactionId, 'queue_member_id' => $userId)); //, 'makequeue_status' => BAQQueueLine::makeQueueStatus_MakeQueue));
        //return last item for queue
        $mTranQueue = end($mTranQueues);

        if ($mTranQueue != NULL) {
            $makeQueueStatus['queueNumber'] = $mTranQueue->queue_number;
            $makeQueueStatus['makeQueueStatus'] = $mTranQueue->makequeue_status;
            $mQueueData = unserialize($mTranQueue->data);
            if ($makeQueueStatus['makeQueueStatus'] == BAQQueueLine::makeQueueStatus_Canceled)
                $makeQueueStatus['cancelQueueTime'] = date(DATE_ATOM, $mQueueData[BAQQueueLine::makeQueueStatus_cancelQueueTime]);
            else
                $makeQueueStatus['makeQueueTime'] = date(DATE_ATOM, $mQueueData[BAQQueueLine::makeQueueStatus_MakeQueueTime]);
            $makeQueueStatus['processQueueStatus'] = $mTranQueue->processqueue_status;

            //get message of queue
            $messages = array();
            $mQueueMessages = BMAOnlineQueueMessage::model()->findAllBySql(
                    'select * from bln_app_onlinequeue_message where  queue_number = :QueueNumber and queue_transaction_id = :TransactionId order by send_time desc  ', array(':QueueNumber' => $mTranQueue->queue_number, 'TransactionId' => $transactionId));
            foreach ($mQueueMessages as $mMessage) {
                $message = array();
                $message['id'] = $mMessage->_id;
                $message['transactionId'] = $mMessage->queue_transaction_id;
                $message['queueNumber'] = $mMessage->queue_number;
                $message['senderId'] = $mMessage->sender_id;
                $message['sendTime'] = $mMessage->send_time;
                $message['message'] = $mMessage->data;
                //$message['sender'] = new BUser($mMessage['sender_id']);

                $messages[$mMessage->_id] = $message;
            }
            $makeQueueStatus['queueMessages'] = $messages;
        }


        $allPendingQueues = BMServiceQueueLineTransactionQueue::model()->findAllByAttributes(
                array('transaction_id' => $transactionId, 'processqueue_status' => BAQQueueLine::processQueueStatus_Pending));

        if (isset($makeQueueStatus['queueNumber'])) {
            $allPendingQueues = BMServiceQueueLineTransactionQueue::model()->findAllBySql(
                    'select * from bln_app_onlinequeue_service_queueline_transaction_queue 
                        where transaction_id = :TransactionId and processqueue_status = :ProcessStatus and queue_number < :QueueNumber', array(':TransactionId' => $transactionId,
                ':ProcessStatus' => BAQQueueLine::processQueueStatus_Pending,
                'QueueNumber' => $makeQueueStatus['queueNumber']
                    ));
        }

        $pendingCount = count($allPendingQueues);

        $makeQueueStatus['pendingQueue'] = $pendingCount;

        //get waiting time in minutes     
        $waitingTime = -1;
        if ($averageProcessTime > 0 && $pendingCount > 0) {
            $waitingTime = $averageProcessTime * $pendingCount;
            $estimateTime = '';

            $waitingSeconds = $waitingTime % 60;
            $waitingMins = (($waitingTime - $waitingSeconds) % (60 * 60)) / 60;
            $waitingHours = ($waitingTime - $waitingSeconds - $waitingMins * 60) / (60 * 60);

            if ($waitingHours > 0)
                $estimateTime = $waitingHours . ' hours';
            if ($waitingMins > 0)
                $estimateTime .= $waitingMins . ' minutes';
            if ($waitingSeconds > 0)
                $estimateTime .= $waitingSeconds . ' seconds';
            $makeQueueStatus['estimateWaitingTime'] = $estimateTime;
        }

        return $makeQueueStatus;
    }

    /**
     * 
     * 
     * 
     * @return BAQQueueLine
     */
    public function getActiveQueueLine() {
        $qLindId = $this->getTransitVariable('activeQueueLineId');
        return BAQQueueLine::find(array(BAQQueueLine::key_QueueLineId => $qLindId));
    }

}

?>
